<?php
class Account extends Controller {
	function Account()
	{
		parent::Controller();
		
		global $BBX;
		$this->load->vars(array('BBX' => $BBX));
	}
	
	// simple, readable, high-entropy random word for use with the captcha plugin
	function _rand_word()
	{
		return strtolower(substr(preg_replace('/[^abcdefghkmnpqrstwxy2-9]/i',
							'',
							base64_encode(time()*rand(1,9999))), 0, 6));
	}
	
	function deprecated_member_profile()
	{
		global $BBX;
		
		$this->load->model('Bricabox_model');
		$this->load->model('Membership_model');
		
		// is this user a member?
		$login = $this->uri->segment(2);
		if (!$this->Membership_model->is_member_of($BBX['bricabox']->id, $login))
			$non_member = true;
		else
			$non_member = false;
		
		$this->load->helper('typography');
		$this->load->helper('text');
		$this->load->helper('url');
		$this->load->helper('date');
		
		$page  = $this->uri->segment(3, 1); // default to 1
		$query = $this->db->query('select * from users where login = ?', array($login));
		$user  = $query->first_row();
		
		$data = array(
			'non_member'	=> $non_member,
			'BBX'			=> $BBX,
			'bricabox' 		=> $BBX['bricabox'],
			'mem_user'		=> $user,
			'page_title'	=> "{$BBX['bricabox']->name}: Members &rsaquo; ".username($user),
			'comments'		=> $this->db->query('select * from profile_comments
				where user_id = ?
				 	and author_id in (select user_id from memberships where bricabox_id = ?)
				order by created_at desc', array($user->id, $BBX['bricabox']->id))
		);
		$this->load->view('account/member_profile', $data);
	}
	
	function member_profile()
	{
		$this->global_profile(false);
	}
	
	function global_profile($global = true)
	{
		global $BBX;
		
		$this->load->model('Bricabox_model');
		$this->load->model('Membership_model');
		
		// is this user a member?
		if (!$global)
		{
			$login = $this->uri->segment(2);
			if (!$this->Membership_model->is_member_of($BBX['bricabox']->id, $login))
				$non_member = true;
			else
				$non_member = false;
		}
		
		$this->load->helper('typography');
		$this->load->helper('text');
		$this->load->helper('url');
		$this->load->helper('date');
		
		$login = $this->uri->segment(2);
		$page  = $this->uri->segment(3, 1); // default to 1
		
		//if (strpos($login, ':') !== false)
		//{
		//	// alias
		//	$query = $this->db->query('select * from users
		//		where url_alias = ?', array(str_replace('u:', '', $login)));
		//	if (!$query->num_rows())
		//	{
		//		show_404();
		//		exit();
		//	}
		//}
		//else
		//{
			// login or alias
			$query = $this->db->query('select * from users where login = ? or url_alias = ?', array($login, $login));
		//}
		$user = $query->first_row();
		
		$this->load->model('Activity_model');
		
		if ($global)
		{
			$data = array(
				'activity'		=> $this->Activity_model->get_activity(array('actor_id' => $user->id)),
				'contactivity'		=> $this->Activity_model->get_activity(array('contacts_of' => $user->id)),
				'mem_user'		=> $user,
				'page_title'	=> username($user),
				'comments'		=> $this->db->query('select * from profile_comments
					where user_id = ? order by created_at desc', array($user->id))
			);
		}
		else
		{
			$data = array(
				'activity'		=> $this->Activity_model->get_activity(array('actor_id' => $user->id, 'bricabox_id' => $BBX['bricabox']->id)),
				'contactivity'		=> $this->Activity_model->get_activity(array('contacts_of' => $user->id, 'bricabox_id' => $BBX['bricabox']->id)),
				'non_member'	=> $non_member,
				'BBX'			=> $BBX,
				'bricabox' 		=> $BBX['bricabox'],
				'mem_user'		=> $user,
				'page_title'	=> "{$BBX['bricabox']->name}: Members &rsaquo; ".username($user),
				'comments'		=> $this->db->query('select * from profile_comments
					where user_id = ?
					 	and author_id in (select user_id from memberships where bricabox_id = ?)
					order by created_at desc', array($user->id, $BBX['bricabox']->id))
			);
		}
		$data['following'] = $this->db->query("SELECT users.* FROM users
			WHERE users.id IN
				(SELECT followed_user_id FROM followers
					WHERE user_id = ?)",
			$user->id);
		$this->load->view('account/' . ($global ? 'global_profile' : 'member_profile'), $data);
	}
	
	/*
	* Global profile using Modelicious
	*/
	function superstar()
	{
		show_404();
		exit();
		
		$this->output->enable_profiler(true);
		
		global $BBX;
		
		$this->load->helper('typography');
		$this->load->helper('text');
		$this->load->helper('url');
		$this->load->helper('date');
		
		$login = $this->uri->segment(2);
		$page  = $this->uri->segment(3, 1); // default to 1
		$User  = $this->modelicious->User();
		$profile_user = $User->find_by('login', $login);
		
		$data = array(
			'User'			=> $User,
			'mem_user'		=> $profile_user,
			'page_title'	=> username($profile_user),
			'comments'		=> $this->db->query('select * from profile_comments where user_id = ? order by created_at desc', array($profile_user->id))
		);
		$this->load->view('account/global_profile_mc', $data);
	}
	
	function sign_up_or_log_in()
	{
		// we have to redirect to the root site if this is a bricabox on a custom domain
		global $BBX;
		if (isset($BBX['custom_domain']))
		{
			header('Location: '.APP_ROOT_URL.'/sign_up_or_log_in');
		}
		elseif (isset($BBX['bricabox']) && $BBX['bricabox']->subdomain)
		{
			header('Location: '.APP_ROOT_URL.'/sign_up_or_log_in');
		}
		
		$this->load->model('Redirect_model');
		$this->load->plugin('captcha');
		
		// set up the captcha
		$vals = array(
			'word'	   => $this->_rand_word(),
			'img_path' => BASEPATH.'../assets/images/captcha/',
			'img_url'  => '/assets/images/captcha/'
		);
		$cap = create_captcha($vals);
		
		$token = $this->userland->store_location();
		$this->userland->redirect_if_logged_in();
		
		$_rd = $this->Redirect_model->load_redirect_by_token($token);
		if ($_rd->bricabox_id > 0)
			$_bricabox = $this->db->query('select name from bricaboxes where id = ?',
				array($_rd->bricabox_id))->first_row();
		else
			$_bricabox = false;
		
		$data = array(
			'page_title' => 'Sign up or log in to BricaBox',
			'token' 	 => $token,
			'back_to'	 => $_bricabox,
			'cap'		 => $cap
		);
		$this->load->view('account/log_in', $data);
	}
	
	function log_out()
	{
		// if this is a custom domain, see if the user wants to log out of bricabox completely
		global $BBX;
		if (isset($BBX['custom_domain']))
		{
			$this->userland->logout(false);
			$this->load->view('account/logout_all', array('bricabox_name' => $BBX['bricabox']->name));
		}
		else
			$this->userland->logout();
	}
	
	function auth_openid_finish()
	{
		// we expect a url in this format:
		// /account/auth_openid_finish/token/xxxxx/id_hash/xxxxx/[optional/sreg/params/here]
		$pairs = $this->uri->uri_to_assoc(3);
		$decoded_id = url_safe_base64($pairs['id_hash'], 'decode');
		
		// now comes the real fun; we need to do the following:
		// 1. look for a user whose identity_url matches the decoded id_hash
		// 2a. if we find one, great; we're done (for now)
		// 2b. if not, we have to create a new user record
		//
		// also, if encoded sreg data is passed in, decode and parse it
		$user = $this->userland->find_user_by_openid($decoded_id);
		if (!$user)
		{
			$sreg = array();
			if (isset($pairs['sreg']))
			{
				$_sreg = $pairs['sreg'];
				$_sreg = url_safe_base64($_sreg, 'decode');
				$_sreg_pairs = explode('|', $_sreg);
				foreach ($_sreg_pairs as $p)
				{
					list($k, $v) 	= explode(':', $p);
					$sreg[$k] 		= $v;
				}
			}
			$user = $this->userland->create_user_from_openid($decoded_id, $sreg);
		}
		
		// now that we have a user, we can spoof a POST and log 'em in
		$data = array(
			'safe_identity_url'	=> url_title($decoded_id),
			'password'			=> sha1("{$decoded_id}--kicks--ass--03291986"),
			'token'				=> $pairs['token']
		);
		$this->load->view('account/openid_login_spoof', $data);
	}
	
	function auth_openid()
	{
		$_failed	= true;
		$openid_url = prep_url($this->input->post("openid"));
		$token 		= $this->uri->segment(3);
		if (strlen($openid_url) > 7) // more than just http://
		{
			$consumer 		= create_consumer();	
			$auth_request 	= $consumer->begin($openid_url);
			if (!$auth_request)
				$_failed = true;
			else
			{
				// clear our failed flag and attach an sreg request to the auth req
				$_failed		= false;
				$sr_reqd		= array(); // required
				$sr_opt			= array('nickname', 'email'); // optional
				$sreg_request 	= Auth_OpenID_SRegRequest::build($sr_reqd, $sr_opt);
				if ($sreg_request)
					$auth_request->addExtension($sreg_request);
					
				// set up urls
				$urls = build_openid_urls($token);
				
				// redirect
				// todo: add error checking here (see try_auth.php for examples)
				if ($auth_request->shouldSendRedirect())
				{
					// v1 uses a redirect header
					$redirect_url = $auth_request->redirectURL($urls['trust_root'], $urls['redirect']);
					header("Location: {$redirect_url}");
					exit();
				}
				else
				{
					// v2 uses a javascript form POST to redirect
					$form_id 	= 'openid_redirect';
					$form_html 	= $auth_request->formMarkup($urls['trust_root'], $urls['redirect'], false, array('id' => $form_id));
					$this->load->view('account/openid_form', array('yield' => $form_html, 'id' => $form_id));
				}
			}
		}
		
		if ($_failed)
		{
			$this->load->model('Redirect_model');
			$_rd = $this->Redirect_model->load_redirect_by_token($token);
			if ($_rd->bricabox_id > 0)
				$_bricabox = $this->db->query('select name from bricaboxes where id = ?',
					array($_rd->bricabox_id))->first_row();
			else
				$_bricabox = false;
			
			// set up the captcha
			$this->load->plugin('captcha');
			$vals = array(
				'word'	   => $this->_rand_word(),
				'img_path' => BASEPATH.'../assets/images/captcha/',
				'img_url'  => '/assets/images/captcha/'
			);
			$cap = create_captcha($vals);
			
			$this->flashy->save_flash('error', 'Please check your OpenID and try again.');
			$data = array(
				'openid'  	=> $openid_url,
				'token' 	=> $token,
				'back_to'	=> $_bricabox,
				'cap'		=> $cap
			);
			$this->load->view('account/log_in', $data);
		}
	}
	
	function auth()
	{
		$login = $this->input->post("login", true);
		$pass  = $this->input->post("password", true);
		$token = $this->uri->segment(3);
		if ($this->userland->authenticate($login, $pass))
		{
			// Log the login
			log_message('debug', 'LOGIN ' . $login);
			
			$enc_pass = $this->userland->save_user_cookie($login, $pass);
			$this->userland->redirect_back($token, $login, $enc_pass);
		}
		else
		{
			$this->load->model('Redirect_model');
			$this->load->plugin('captcha');
			
			// set up the captcha
			$vals = array(
				'word'	   => $this->_rand_word(),
				'img_path' => BASEPATH.'../assets/images/captcha/',
				'img_url'  => '/assets/images/captcha/'
			);
			$new_cap = create_captcha($vals);
			
			$_rd = $this->Redirect_model->load_redirect_by_token($token);
			if ($_rd->bricabox_id > 0)
				$_bricabox = $this->db->query('select name from bricaboxes where id = ?',
					array($_rd->bricabox_id))->first_row();
			else
				$_bricabox = false;
			
			$this->flashy->save_flash('error', 'Please check your username and password and try logging in again.');
			$data = array(
				'login'  => $login,
				'token'  => $token,
				'back_to' => $_bricabox,
				'cap'	 => $new_cap
			);
			$this->load->view('account/log_in', $data);
		}
	}
	
	function login_success()
	{
		global $BBX;
		
		$this->load->model('Redirect_model');
		
		$token = $this->uri->segment(3);
		$login = $this->uri->segment(4);
		$pass  = $this->uri->segment(5);
		
		// create the cookies for this domain as well
		$domain = ".{$BBX['request']['subless_portless_host']}";
		$this->userland->save_user_cookie($login, $pass, $domain, true); // don't re-encrypt
		
		// now redirect to the true return url
		$this->Redirect_model->redirect_to($token, true);
	}
	
	function recover_password()
	{
		global $BBX;
		
		if ($this->userland->logged_in())
			header("Location: /");
		
		$this->load->view('account/recover_password');
	}
	
	function send_password()
	{
		global $BBX;
		
		$login = $this->input->post('login', true);
		if ($login)
		{
			if (strpos($login, '@') !== false)
				$which = 'email';
			else
				$which = 'login';
			$query = $this->db->query('select id,salt,email,login from users where '.$which.' = ? limit 1', array($login));
			if ($query->num_rows() == 1)
			{
				$user_id = $query->first_row()->id;
				
				// generate a new password, save it, and email it to them
				$rnd	  = substr(sha1(time()*rand(1,999)), 0, 8);
				$new_pass = $this->userland->encrypt_pass($rnd, $query->first_row()->salt);
				$this->db->query('update users set crypted_password = ? where id = ?', array($new_pass, $query->first_row()->id));
				
				$this->emailer->deliver_new_password(array(
					'to'		=> $query->first_row()->email,
					'subject'	=> "Here is your new BricaBox ID password",
					'data'		=> array(
						'data' => array(
							'password'	=> $rnd,
							'login'		=> $query->first_row()->login
						)
					)
				));
				
				$this->flashy->save_flash('notice', "Your new password was emailed to {$query->first_row()->email}.");
				header("Location: /sign_up_or_log_in");
			}
			else
			{
				// invalid
				$this->flashy->save_flash('error', 'Unknown BricaBox ID or email address');
				$this->load->view('account/recover_password', array('login' => $login));	
			}
		}
		else
		{
			// nothing
			$this->flashy->save_flash('error', 'Unknown BricaBox ID or email address');
			$this->load->view('account/recover_password');
		}
	}
	
	function check_captcha($str)
	{
		// trim leading/trailing spaces, remove inner whitespace; case insensitive
		if (md5(strtolower(trim(preg_replace('/\s+/', '', $str)))) == $this->input->post('captcha_val'))
			return true;
		else
		{
			$this->validation->set_message('check_captcha', "The text you entered doesn't match the text displayed in the box below.");
			return false;
		}
	}
	
	function check_email($str)
	{
		$query = $this->db->query('select id from users where email = ?', array($str));
		if ($query->num_rows == 0)
			return true;
		else
		{
			$this->validation->set_message('check_email', 'The email address you gave is already taken.');
			return false;
		}
	}
	
	function check_username($str)
	{
		$query = $this->db->query('select id from users where login = ?', array($str));
		if ($query->num_rows == 0)
			return true;
		else
		{
			$this->validation->set_message('check_username', 'The BricaBox ID you chose is already in use.');
			return false;
		}
	}
	
	function check_terms($str)
	{
		if ((bool)$str === false)
		{
			$this->validation->set_message('check_terms', 'You must accept the Terms of Service.');
			return false;
		}
		else
			return true;
	}
	
	function create_account()
	{
		$this->load->plugin('captcha');
		$this->load->library('validation');
		$this->load->model('Redirect_model');
		
		$token = $this->uri->segment(3);
		
		// validations
		$rules['login']			= "required|trim|alpha_numeric|callback_check_username";
		$rules['email']			= "required|trim|valid_email|callback_check_email";
		$rules['captcha']	 	= "required|trim|callback_check_captcha";
		$rules['password']		= "required|matches[confirm_password]";
		$rules['confirm_password'] = "required";
		$rules['tos']			= "required|callback_check_terms";
		$this->validation->set_rules($rules);
		
		$fields['login'] 	= "BricaBox ID";
		$fields['email'] 	= "email address";
		$fields['password'] = "password";
		$fields['confirm_password'] = "password confirmation";
		$fields['captcha'] = "captcha";
		$fields['tos']		= "Terms of Service";
		$this->validation->set_fields($fields);
		
		// set up the captcha
		$vals = array(
			'word'	   => $this->_rand_word(),
			'img_path' => BASEPATH.'../assets/images/captcha/',
			'img_url'  => '/assets/images/captcha/'
		);
		$new_cap = create_captcha($vals);
		
		// return to bricabox
		$_rd = $this->Redirect_model->load_redirect_by_token($token);
		if ($_rd->bricabox_id > 0)
			$_bricabox = $this->db->query('select name,privacy,members_must_apply,id from bricaboxes where id = ?',
				array($_rd->bricabox_id))->first_row();
		else
			$_bricabox = false;
		
		// view data
		$data = array(
			'token'   => $token,
			'back_to' => $_bricabox,
			'cap'	  => $new_cap
		);
		
		if ($this->validation->run() === false)
		{
			// validations failed
			$this->load->view('account/log_in', $data);
		}
		else
		{
			// captcha is okay, so continue; create the account
			$salt = sha1(time()*rand(1,1000));
			$pass = $this->userland->encrypt_pass($this->input->post('password'), $salt);
			$_params = array(
				'login' 	=> $this->input->post('login', true),
				'url_alias' => $this->input->post('login', true),
				'salt'		=> $salt,
				'crypted_password' => $pass,
				'email'		 => $this->input->post('email', true),
				'created_at' => mysql_now(),
				'updated_at' => mysql_now(),
				'notify_comments' => 1
			);
			$this->db->insert('users', $_params);
			
			// add the user as a member if possible
			if ($_bricabox !== false)
			{
				// bricabox must be public and not require application
				if ($_bricabox->privacy > 0 && !$_bricabox->members_must_apply)
				{
					$this->load->model('Membership_model');
					$this->Membership_model->add_member($_bricabox->id, $_params['login']);
				}
			}
			
			// add to our CM mailing list
			$this->userland->add_to_cm($_params['login'], $_params['email']);
			
			// send email to new user
			$this->emailer->deliver_signed_up(array(
				'to'		=> $_params['email'],
				'subject'	=> "Welcome to BricaBox!",
				'data'		=> array(
					'data' => array(
						'user' 		=> $_params['login'],
						'url' 		=> APP_ROOT_URL
					)
				)
			));
			
			// spoof a POST to login; this will allow handling custom domain logins, etc.
			echo <<<HTML
<html>
<head>
	<title>r0x0rz</title>
</head>
<body>
	<form action="/account/auth/{$token}" method="post" id="loginform">
		<input type="hidden" name="login" value="{$this->input->post('login')}" />
		<input type="hidden" name="password" value="{$this->input->post('password')}" />
		<input type="submit" value="Continue" />
	</form>
	<script type="text/javascript" charset="utf-8">
		document.getElementById('loginform').submit();
	</script>
</body>
</html>
HTML;
		}
	}
	
	function edit()
	{
		// we have to redirect to the root site if this is a bricabox on a custom domain
		global $BBX;
		if (isset($BBX['custom_domain']))
		{
			header('Location: '.APP_ROOT_URL.'/account/edit');
		}
		elseif (isset($BBX['bricabox']) && $BBX['bricabox']->subdomain)
		{
			header('Location: '.APP_ROOT_URL.'/account/edit');
		}
		
		// logged in?
		if (!$this->userland->logged_in())
		{
			echo "<html><body>Redirecting...<form id=\"loginform\" action=\"/sign_up_or_log_in\" method=\"post\"></form><script type=\"text/javascript\" charset=\"utf-8\">
				document.getElementById('loginform').submit();
			</script></body></html>";
			exit();
		}
			
		$data = array(
			'page_title' => 'Edit your account'
		);	
		
		$this->load->view('account/edit_account', $data);
	}
	
	function save_account()
	{
		if (!$this->userland->logged_in())
			show_404();
		
		$params = $this->input->post('user', true);
		$user	= $this->userland->current_user();
		
		// required stuff
		$this->load->library('validation');
		$this->load->model('Content_model');
		
		$save = true;
		
		// validations
		if ($params['email'] == "") // <-- check for valid email
		{
			$this->flashy->save_flash('error', "You must provide a valid email address.");
			$save = false;
		}
		
		// check that the email is not in use
		if ($user->email != $params['email'])
		{
			$query = $this->db->query('select id from users where email = ? and login <> ?', array($params['email'], $user->login));
			if ($query->num_rows())
			{
				$this->flashy->save_flash('error', "Sorry, that email address is already in use.");
				$save = false;
			}
		}
		
		if (!empty($params['url_alias']))
		{
			if (!$this->check_url_alias(false, $params['url_alias']))
			{
				$save = false;
				$this->flashy->save_flash('error', 'Sorry, that profile url is not available.');
			}
		}
		
		// change password
		$pass_msg		= "";
		$new_pass 		= $this->input->post('password');
		$new_pass_conf  = $this->input->post('password_conf');
		if ($new_pass !== false && $new_pass_conf !== false && $new_pass != "" && $new_pass_conf != "")
		{
			// yep, change their password if the two match
			if ($new_pass != $new_pass_conf)
				$this->flashy->save_flash('error', "The passwords you typed didn't match, so your password was not changed.");
			else
			{
				$salt	  = $user->salt;
				$new_p	  = $this->userland->encrypt_pass($new_pass, $salt);
				
				$this->db->query('update users set crypted_password = ? where id = ?', array($new_p, $user->id));
				
				// update the cookie
				$this->userland->logout(false); 										// no redirect
				$this->userland->save_user_cookie($user->login, $new_p, false, true);	// passing already encrypted pass so don't re-encrypt
				
				$pass_msg = " Also, your password has been changed.";
			}
		}
		
		// avatar
		$r = $this->Content_model->upload_avatar($user->id,
							 $_FILES['user']['tmp_name']['avatar'],
							 $_FILES['user']['name']['avatar'],
							 'user');
							
		if ($r)
			$params['avatar'] = $_FILES['user']['name']['avatar'];
		
		// CM stuff
		if (!$params['optinnewsletter'])
		{
			// unsubscribe
			$cm_ret = $this->userland->add_to_cm($user->login, $params['email'], false);
		}
		elseif ($params['optinnewsletter'])
		{
			// re-subscribe
			$cm_ret = $this->userland->add_to_cm($user->login, $params['email'], true);
		}
		
		
		// save the data
		if ($save)
		{
			$params['url_alias'] 	= !empty($params['url_alias']) ? $params['url_alias'] : $user->login;
			$user->url_alias 		= $params['url_alias'];
			$this->db->where('id', $user->id);
			$this->db->update('users', $params);
			$this->flashy->save_flash('notice', "Your settings have been saved.{$pass_msg}");
			header("Location: /person/" . user_url($user));
		}
		else
		{
			$this->edit();
		}
	}
	
	function check_url_alias($full = true, $alias = null)
	{
		$taken	   = false;
		$login	   = $this->userland->current_user()->login;
		$url_alias = trim(preg_replace('/[^a-z0-9]/i', '', ($full ? $this->input->post('url_alias') : $alias)));
		
		// Empty?
		if (!(int)strlen($url_alias))
		{
			$taken = true;
		}
		
		// Disallowed chars?
		if ($url_alias != ($full ? $this->input->post('url_alias') : $alias))
		{
			$taken = true;
		}
		
		// Do the checkin'
		if ($url_alias == $login)
		{
			// Okay because it's this user's login
		}
		else
		{
			// Make sure it's not taken, either by another login or url_alias unless it's our own record
			$query = $this->db->query('select id from users
				where (url_alias = ? or login = ?)
				and id <> ?', array($url_alias, $url_alias, $this->userland->current_user()->id));
			if ($query->num_rows())
				$taken = true;
		}
		
		// Render the message
		if ($taken)
		{
			$msg = 'Sorry, that URL is already in use or not available.';
			$hex = 'c00';
		}
		else
		{
			$msg = 'Great, that URL is available!';
			$hex = '66bc29';
		}
		
		if ($full)
			echo '<span style="color: #' . $hex . ';">' . $msg . '</span>';
		else
			return (bool)!$taken;
	}
	
	function save_comment()
	{
		global $BBX;
		
		$user  = $this->input->post('username');
		$scope = $this->input->post('scope');
			
		$params = $this->input->post('comment');
		$params['created_at'] = mysql_now();
		$params['updated_at'] = $params['created_at'];
		$this->db->insert('profile_comments', $params);
		
		// email 'em if they allow it
		$email_user = $this->db->query('select id,login,email,notify_comments,
			url_alias,identity_url,display_name from users
			where login = ?', $user);
		$email_user = $email_user->first_row();
		
		// get author data
		$_author_data = $this->db->query('select login,display_name,identity_url from users
			where id = ?', array($params['author_id']))->first_row();
		
		// add to activity stream
		$this->load->model('Activity_model');
		$this->Activity_model->log_comment(array(
			'user_id' => $email_user->id,
			'subject' => username($_author_data),
			'object'  => username($email_user),
			'extra'	  => $params['text']
		));
		
		if ($params['user_id'] != $params['author_id'] && $email_user->notify_comments && strlen($email_user->email)) // don't send for self-comments
		{
			$email_author = user_url($this->db->query('select login,url_alias from users where id = ?', array($params['author_id']))->first_row());
			$this->emailer->deliver_profile_comment(array(
				'to'		=> $email_user->email,
				'subject'	=> "Someone commented on your profile",
				'data'		=> array(
					'data' => array(
						'user' 		=> $user,
						'author'	=> $email_author,
						'url' 		=> str_replace('://.', '://', bricabox_url($BBX['bricabox']))."/{$scope}/{$email_author}",
						'comment'	=> $params['text']
					)
				)
			));
		}
		
		$this->flashy->save_flash('notice', "Great! Your comment has been posted.");
		
		if ($email_user->login != $email_user->url_alias)
			$user = $email_user->url_alias;
		header("Location: /{$scope}/{$user}");
	}
	
	public function follow()
	{
		global $BBX;
		
		$login = $this->uri->segment(3);
		$scope = $this->uri->segment(2);
		
		if (!$login || !$scope)
			die();
		
		$_user   = $this->db->query("SELECT * FROM users WHERE url_alias = ?", $login)->first_row();
		$user_id = $_user->id;
		
		if (!$user_id || !$_user)
			die();
		
		if ($user_id == $this->userland->current_user()->id)
			die();
		
		if ($scope == 'member')
		{
			$back_to = bricabox_url($BBX['bricabox']) . "/member/{$login}";
		}
		else
		{
			$back_to = APP_ROOT_URL . "/person/{$login}";
		}
		
		$params = array($this->userland->current_user()->id, $user_id);
		$query  = $this->db->query("SELECT * FROM followers WHERE user_id = ? AND followed_user_id = ? LIMIT 1",
			$params);
		
		if (!$query->num_rows())
		{
			// Follow
			$this->db->query("INSERT INTO followers VALUES(NULL,?,?)",
				$params);
				
			// Log it
			$this->load->model('Activity_model');
			$this->Activity_model->log_activity(array(
				'action' 		=> 'is following',
				'activity_type' => 'follow',
				'user_id'		=> $_user->id,
				'object'		=> username($_user),
				'subject'		=> username($this->userland->current_user())
			));
			
			// Send email
			if ($_user->notify_following)
			{
				$this->emailer->deliver_new_follower(array(
					'to'		=> $_user->email,
					'subject'	=> username($this->userland->current_user()) . " is following you on BricaBox",
					'data'		=> array(
						'data' => array(
							'user' 		=> username($_user),
							'follower'	=> username($this->userland->current_user()),
							'url' 		=> APP_ROOT_URL . '/person/' . user_url($this->userland->current_user())
						)
					)
				));
			}
		}
		else
		{
			// Unfollow
			$this->db->query("DELETE FROM followers WHERE user_id = ? and followed_user_id = ? LIMIT 1",
				$params);
		}
		
		header("Location: {$back_to}");
		exit;
	}
	
	
	
	
	
	
	function deprecated_sign_up()
	{
	}
	
	function deprecated_log_in()
	{
		// we have to redirect to the root site if this is a bricabox on a custom domain
		global $BBX;
		if (isset($BBX['custom_domain']))
		{
			header('Location: http://notorganized.com:3000/log_in');
		}
		
		$token = $this->userland->store_location();
		$this->userland->redirect_if_logged_in();
		
		$data = array(
			'page_title' => 'Log in',
			'token' 	 => $token
		);
		$this->load->view('account/log_in', $data);
	}
	
	//
	// one-time migrations go below; invoke using /account/*
	//
	
	//function cached_count()
	//{
	//	$this->load->database();
	//	$query = $this->db->query('select id from contents');
	//	foreach ($query->result() as $c)
	//	{
	//		$_query = $this->db->query('select count(*) as count_all from engagements where content_id = ?', array($c->id))->first_row()->count_all;
	//		echo "updating content id {$c->id} to have {$_query} engagements<br />";
	//		$this->db->query('update contents set cached_eng_count = ? where id = ?', array($_query, $c->id));
	//	}
	//}
	
	// migration
	//function migrate_openids()
	//{
	//	$this->load->database();
	//	
	//	$query = $this->db->query('select * from users where identity_url is not null and identity_url <> ""');
	//	foreach ($query->result() as $user)
	//	{
	//		echo "converting user {$user->identity_url}<br />";
	//		
	//		$identity_url = $user->identity_url;
	//		$params['login'] = url_title($identity_url);
	//		echo "-- login = {$params['login']}<br />";
	//		
	//		$pass_str 	= sha1("{$identity_url}--kicks--ass--03291986");
	//		$salt 		= sha1(time().$identity_url."--openid--rules");
	//		$pass 		= $this->userland->encrypt_pass($pass_str, $salt);
	//		echo "-- passstr = {$pass_str}<br />";
	//		echo "-- salt = {$salt}<br />";
	//		echo "-- pass = {$pass}<br />";
	//		
	//		$params['crypted_password'] = $pass;
	//		$params['salt']				= $salt;
	//		
	//		print_r($params);
	//		
	//		$this->db->where('identity_url', $identity_url);
	//		$this->db->limit(1);
	//		$this->db->update('users', $params);
	//	}
	//}
}
?>